package com.ict.txmsv2.controller;

import com.ict.txmsv2.model.ChatMsg;
import com.ict.txmsv2.model.Message;
import com.ict.txmsv2.model.User;
import com.ict.txmsv2.model.WsData;
import com.ict.txmsv2.services.MessageService;
import com.ict.txmsv2.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author linzzz
 * @desc ...
 * @date 2020-12-20
 */
@Controller
public class WsController {
    @Autowired
    MessageService messageService;
    @Autowired
    UserService userService;

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/ws/chat")
    public void handleMsg(Authentication authentication, ChatMsg chatMsg){
        User user = (User) authentication.getPrincipal();
        chatMsg.setFrom(user.getUsername());
        chatMsg.setFromNickName(user.getName());
        chatMsg.setDate(new Date());
        Message message = new Message();
        message.setContent(chatMsg.getContent());
        message.setFromid(user.getId());
        message.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(chatMsg.getDate()));
        Integer toId = userService.getIdByUserName(chatMsg.getTo());
        if(toId == null){
            return;
        }
        message.setToid(toId);
        messageService.insertMessage(message);
        simpMessagingTemplate.convertAndSendToUser(chatMsg.getTo(),"/queue/chat",chatMsg);
    }

    @GetMapping("/chatRecord")
    @ResponseBody
    public WsData getAllMessageByUserId(Authentication authentication){
        User user = (User) authentication.getPrincipal();
        WsData wsData = new WsData();
        List<Message> messages = messageService.getAllMessageByUserId(user.getId());
        HashMap<String, List<Message>> map = new HashMap<>();
        HashMap<String,Integer> usersRead = new HashMap<> ();
        for (Message message : messages) {
            if(message.getFromid().equals(user.getId())){
                String key = user.getUsername()+'#'+message.getToName();
                List<Message> orDefault = map.getOrDefault(key, new ArrayList<>());
//                if(!message.getStatus()){
//                    Integer od = usersRead.getOrDefault(key, 0);
//                    usersRead.put(key,od+1);
//                }
                message.setSelf(true);
                orDefault.add(message);
                map.put(key,orDefault);
            }else{
                String key = user.getUsername() + "#"+message.getFromName();
                List<Message> orDefault = map.getOrDefault(key, new ArrayList<>());
                if(!message.getStatus()){
                    Integer od = usersRead.getOrDefault(key, 0);
                    usersRead.put(key,od+1);
                }
                message.setSelf(false);
                orDefault.add(message);
                map.put(key,orDefault);
            }
        }
        wsData.setUsersRead(usersRead);
        wsData.setSessions(map);
        return wsData;
    }

    @PutMapping("/chatRecord/{toId}")
    @ResponseBody
    public void readMessage(Authentication authentication,@PathVariable Integer toId){
        User user = (User) authentication.getPrincipal();
        messageService.readMessage(user.getId(),toId);
    }
}
